package com.nioSocketCore.chapter01;

import java.nio.ByteBuffer;


/**
 * @author : wushikai
 * <p>
 * date : 2022-04-29
 * <p>
 * warp 会重新 设置 空间 ;
 */
public class BufferFlipClearWarp {


    /**
     * 方 法 int remaining()的作用：返回  "当前位置"  与 limit 之间的元素数 。
     */
    public static void main(String[] args) {

        byte[] bytes = {0, 1, 2, 3};

        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer = ByteBuffer.wrap(bytes);
        System.out.println(" A capacity()=" + byteBuffer.capacity() + "   limit() =" + byteBuffer.limit() + "  position()=" + byteBuffer.position());


        byteBuffer.put((byte) 'a');
        byteBuffer.put((byte) 'b');
        byteBuffer.put((byte) 'c');
        System.out.println(" B capacity()=" + byteBuffer.capacity() + "   limit() =" + byteBuffer.limit() + "  position()=" + byteBuffer.position());
//        byteBuffer.put((byte) 7) ;    limit 之后不可写
        byteBuffer.flip();
        System.out.println("after  flip .............. ");


        //byteBuffer.clear();
        System.out.println(" C capacity()=" + byteBuffer.capacity() + "   limit() =" + byteBuffer.limit() + "  position()=" + byteBuffer.position());

//          byteBuffer.put((byte) 7);

        for (int i = 0; i < byteBuffer.capacity(); i++) {
            if (i == byteBuffer.limit()) {
                break;
            }
            System.out.println(byteBuffer.get(i));  //get的范围不能超过 limit ,  否则报错;  limit 之后不可读
        }

        System.out.println(" D capacity()=" + byteBuffer.capacity() + "   limit() =" + byteBuffer.limit() + "  position()=" + byteBuffer.position());

        byteBuffer.clear(); //重置了 buffer 的限制 ;


        System.out.println(" E capacity()=" + byteBuffer.capacity() + "   limit() =" + byteBuffer.limit() + "  position()=" + byteBuffer.position());


   /*     byteBuffer.position(1);
        byteBuffer.mark();
        System.out.println(byteBuffer.position());*/


    }


}
